package com.gmrz.uaf.servlet.v1.filter;

import com.gmrz.service.logpool.LogPoolManager;
import com.gmrz.uaf.common.GuiceUtil;
import com.gmrz.uaf.protocol.v1.schema.FidoLog;
import com.gmrz.uaf.server.ServerContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class ResponseFilter implements Filter {



    private static final Logger LOG = LogManager.getLogger(ResponseFilter.class);
    private static final String CONTENT_TYPE_JSON = "application/json;charset=UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServerContext serverContext = ServerContext.getServerContext();
        try {
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.setCharacterEncoding("utf-8");
            response.setContentType(CONTENT_TYPE_JSON);
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            UAFResponseWrapper responseWrapper = new UAFResponseWrapper(response);
            filterChain.doFilter(servletRequest, responseWrapper);
            //记录日志
            UAFWriter uafWriter = responseWrapper.getUAFWriter();
            if (uafWriter != null) {
                String responseJson = uafWriter.getContent();
                //LOG.info("responseJson:"+responseJson);
                JsonParser parser = new JsonParser();
                JsonElement element = parser.parse(responseJson);
                JsonObject object = element.getAsJsonObject();
                int operCode = object.get("statusCode").getAsInt();
                String operError = object.get("description").getAsString();
                // 从ServerContext中获取之前的fidolog，ServerContext属于线程独有，放在了threadlock中
                FidoLog fidoLog = serverContext.getFidoLog();
                if (fidoLog != null) {
                    fidoLog.setOperCode(operCode);
                    fidoLog.setOperError(operError);
                    fidoLog.setResponse(responseJson);
                    LogPoolManager manager = GuiceUtil.getProcessorInjector().getInstance(LogPoolManager.class);
                    manager.addLog(fidoLog);
                }
            }
        }catch (Exception e){
            LOG.error("error",e);
        }finally {
            serverContext.destroy();
        }
    }

    @Override
    public void destroy() {

    }
}
